package com.atguigu.lease.web.admin.custom.intercepter;

import com.atguigu.lease.common.login.LoginUser;
import com.atguigu.lease.common.login.LoginUserHolder;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author Marco
 * @Description
 * @date 2025/8/5 23:19
 * @email 3293336923@qq.com
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {


//    在调用 handler 方法之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//        从 请求头中 获取 token
        String token = request.getHeader("access-token");

//        获取 payload 对象
        Claims claims = JwtUtil.parseToken(token);


//        从 payload 对象中获取用户信息
        Long userId = claims.get("userId", Long.class);
        String username = claims.get("username", String.class);

//       将 用户的 信息 存储到  ThreadLocal 中
        LoginUserHolder.setLoginUser(new LoginUser(userId , username));

        return  true;
    }


//      TODO  是否是为了 防止 内存泄漏问题
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserHolder.clear();
    }
}
